package com.tcxhb.job.dao.handler;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2022/10/8
 */
@MappedTypes({Map.class})
@MappedJdbcTypes({JdbcType.VARCHAR,JdbcType.BLOB})
public class MapValueHandler extends BaseTypeHandler<Map<String, String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, String> stringListMap, JdbcType jdbcType) throws SQLException {
        String str = toJson(stringListMap);
        ps.setString(i, str);
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, String s) throws SQLException {
        return toBeans(rs.getString(s));
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, int i) throws SQLException {
        return toBeans(rs.getString(i));
    }

    @Override
    public Map<String, String> getNullableResult(CallableStatement cs, int i) throws SQLException {
        return toBeans(cs.getString(i));
    }

    private Map<String, String> toBeans(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        Map<String, String> requestBody = JSON.parseObject(str, Map.class);
        return requestBody;
    }

    private String toJson(Map<String, String> stringMap) {
        return JSON.toJSONString(stringMap);
    }
}
